<template>
  <div style="min-width: 1200px; padding-top: 20px">
    <div class="tradeBox">
      <span class="tradeTop">填写并核对订单信息</span>
      <div class="tradeBody">
        <div class="userInfo box">
          <div class="header">
            <span class="userTitle">收件人信息</span>
            <button class="titleBtn" @click="isShow">添加地址</button>
          </div>
          <div
            class="infoItem"
            v-for="(item, index) in payStore.userAddress"
            :key="index"
          >
            <div class="addressee" :class="{ active: item.isSelected }">
              <span>{{ item.username }}</span>
            </div>
            <div class="address">
              <span>{{ item.allAddress }}</span>
            </div>
            <div class="phone">
              <span>{{ item.phone }}</span>
            </div>
            <button class="defaultBtn" @click="payStore.isCheck(index)">
              默认地址
            </button>
          </div>
        </div>
        <div class="payType box">
          <span class="payTitle">支付方式</span>
          <div class="payTypeList">
            <div class="payItem active">
              <span>在线支付</span>
            </div>
          </div>
        </div>
        <div class="deliverGoods box">
          <span class="">送货清单</span>
          <div class="deliverGoodsInfo">
            <div class="deliveryType">
              <span class="span">配送方式</span>
              <div class="deliveryInfo">
                <div class="btn">
                  <span>{{ `中通快递` }}</span>
                </div>
                <div class="deliveryTime">
                  <span>
                    配送时间：预计 {{ `8月10日（周三）09:00-15:00` }} 送达
                  </span>
                </div>
              </div>
            </div>
            <div class="goodsList">
              <span class="goodsTitle">商品清单</span>
              <div class="goodsItem" v-for="goods in goodsListData.detailArrayList" :key="goods.skuId">
                <img
                  class="goodsImg"
                  :src="goods.imgUrl"
                  alt="图片加载中..."
                />
                <div class="goodInfo">
                  <div class="goodsDes">
                    <span>{{
                      goods.skuName
                    }}</span>
                  </div>
                  <div class="goodspRight">
                    <span>{{ `7天无理由退货` }}</span>
                  </div>
                </div>
                <div class="goodsPrice">
                  <span>单价 ￥ {{ goods.orderPrice }}</span>
                </div>
                <div class="goodsNum">
                  <span>数量 X {{ goods.skuNum }}</span>
                </div>
                <div class="isStock">
                  {{ true ? "有货" : "无货" }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="userDes">
          <span class="userDestitle">买家留言</span>
          <textarea
            v-model="orderComment"
            class="userText"
            placeholder="建议留言前先与商家沟通确认"
          ></textarea>
        </div>
      </div>
      <div class="tradeFooter">
        <div class="goodsPriceInfo">
          <div class="priceItem">
            <span class="infoLeft">共计{{ goodsListData.totalNum }}件商品，总金额</span>
            <span class="infoRight"
              >￥{{ goodsListData.originalTotalAmount || 0 }}</span
            >
          </div>
          <div class="priceItem">
            <span class="infoLeft">返现</span>
            <span class="infoRight">￥{{ "0" }}</span>
          </div>
          <div class="priceItem">
            <span class="infoLeft">运费</span>
            <span class="infoRight">{{ "0.00" }}</span>
          </div>
        </div>
        <div class="goodsPrice">
          <div class="goodsPriceNum">
            <span>应付金额：</span>
            <span class="goodsPeice">￥{{ goodsListData.totalAmount || 0 }}</span>
          </div>
          <br />
          <div class="goodsAddRess">
            <span>
              收货人：
              {{ payStore.userSelect?.username?(payStore.userSelect?.username +' '+ payStore.userSelect?.phone):'暂无，请添加收件人'  }}
            </span>
            <br />
            <br />
            <span>
              寄送至：
              {{ payStore.userSelect?.allAddress||'暂无，添加地址' }}
            </span>
            <br />
            <br />
          </div>
        </div>
        <button class="toPayBtn" @click="toPay">提交订单</button>
      </div>
    </div>
    <Dialog
      v-if="addModel"
      :visible="addModel"
      @isShow="isShow"
      :title="addModeltitle"
      :width="addModelWidth"
    >
      <template #default>
        <div>
          <!-- validation-schema属性值为包含校验规则函数的对象名。
              通过作用域插槽，<Form>可通过解构拿到errors对象给子节点使用。
              errors.username即为校验函数中我们返回的错误文本消息，
              可通过v-if动态提示消息。
          -->
          <!--validation-schema  自定义校验规则 -->
          <!--ref  dom节点 -->
          <Form :validation-schema="schema" ref="formRef" @submit="addAddress">
            <label for="username"> 收件人&emsp;： </label>
            <Field
              v-model="userAddInfo.username"
              class="inp"
              type="text"
              id="username"
              placeholder="请输入收件人姓名"
              name="usernameFn"
            />
            <ErrorMessage class="error-msg" name="usernameFn"></ErrorMessage>
            <br />
            <br />
            <label for="phone"> 手机号码： </label>
            <Field
              v-model="userAddInfo.phone"
              class="inp"
              type="text"
              id="phone"
              placeholder="请输入手机号码"
              name="phoneFn"
            />
            <ErrorMessage class="error-msg" name="phoneFn"></ErrorMessage>
            <br />
            <br />
            <label> 地&emsp;&emsp;址： </label>
            <select
              v-model="addressData.provinceObj"
              placeholder="请选择"
              @change="provinceChange"
              value-key="name"
              class="addressItem"
            >
              <option
                v-for="(item, index) in addressData.provinceData"
                :key="index"
                :value="item.name"
                :label="item.name"
              ></option></select
            >&nbsp;省&nbsp;
            <select
              v-model="addressData.cityObj"
              placeholder="请选择"
              @change="cityChange"
              value-key="name"
              class="addressItem"
            >
              <option
                v-for="(item, index) in addressData.cityData"
                :key="index"
                :label="item.name"
                :value="item.name"
              ></option></select
            >&nbsp;市&nbsp;
            <select
              v-model="addressData.countryObj"
              placeholder="请选择"
              @change="countryChange"
              value-key="name"
              class="addressItem"
            >
              <option
                v-for="(item, index) in addressData.countryData"
                :key="index"
                :label="item.name"
                :value="item.name"
              ></option></select
            >&nbsp;区/县
            <ErrorMessage
              v-show="threeSelect"
              name="selsectFn"
              class="error-msg"
            />
            <br />
            <br />
            <label for="address"> 详细地址： </label>
            <Field
              v-model="userAddInfo.addressInfo"
              placeholder="乡镇街道"
              type="text"
              id="address"
              class="inp"
              name="addressFn"
            />
            <ErrorMessage  name="addressFn" class="error-msg" />
          </Form>
        </div>
      </template>
      <template #footer>
        <div>
          <button @click="addAddress">添加</button>
          <button class="defaultBtn" @click="isShow">取消</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: "STrade",
};
</script>
<script lang="ts" setup>
import { Form, Field, ErrorMessage } from "vee-validate";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import type { UserAddress, Addresss } from "@/stores/interface/pay";
import Dialog from "@/components/Dialog/index.vue";
import ProvinceCityCountry from "@/assets/json/address.json";
import { userPayStore } from "@/stores/pay";
// 支付订单请求
import { reqGetTradeInfo, reqSubmitOrder } from "@/api/pay";
import { phoneReg } from "@/utils/rules";
// pay公共数据
const payStore = userPayStore(); // userAddress
const info = {
  username: "",
  addressInfo: "",
  phone: undefined,
  isSelected: true,
  address: {},
  allAddress: "", // 完整地址
};
// 表单 DOM 对象
const formRef = ref();
// 三级联动下拉框校验
const threeSelect = ref<boolean>(false);
// 表单校验规则
const schema = {
  usernameFn(value){
    if (!value) return "姓名不能为空";
    return true;
  },
  phoneFn(value){
    if (!value) return "手机号不能为空";
    if (!phoneReg.test(value)) return "请填写正确的手机号";
    return true;
  },
  addressFn(value){
    if (!value) return "地址不能为空";
    return true;
  },
  selsectFn(value){
    if (!value) return "地址不能为空";
    return true;
  },
};
// 模态框数据
const userAddInfo = ref<UserAddress>(info);
const router = useRouter();
// 添加地址
// 模态框
const addModel = ref<boolean>(false);
const addModelWidth = ref<string>("60%");
const addModeltitle = ref<string>("添加收件人");
const isShow = async () => {
  threeSelect.value = false;
  addModel.value = !addModel.value;
  userAddInfo.value = {
    username: "",
    addressInfo: "",
    phone: undefined,
    isSelected: true,
    address: {},
    allAddress: "", // 完整地址
  };
  addressData.value = {
    provinceObj: { name: "" }, // 省
    cityObj: { name: "" }, // 市
    countryObj: { name: "" }, // 县
    provinceData: ProvinceCityCountry.address, // 地址数据
    cityData: [],
    countryData: [],
  }
};
// 地址三级分类
const addressData = ref<Addresss>({
  provinceObj: { name: "" }, // 省
  cityObj: { name: "" }, // 市
  countryObj: { name: "" }, // 县
  provinceData: ProvinceCityCountry.address, // 地址数据
  cityData: [],
  countryData: [],
});
// 省份change
const provinceChange = () => {
  // console.log(addressData.provinceObj);
  addressData.value.cityData = addressData.value.provinceData.find(
    (item) => item.name === addressData.value.provinceObj
  )?.children; // 市下拉列表
  addressData.value.countryData = []; // 清空区县下拉列表数据
  addressData.value.cityObj = ""; // 清空市输入框内容
  addressData.value.countryObj = ""; // 清空区县输入框内容
};
// 市change
const cityChange = () => {
  addressData.value.countryData = addressData.value.cityData?.find(
    (item) => item.name === addressData.value.cityObj
  )?.children; // 县区下拉框列表
  addressData.value.countryObj = ""; // 清空区县输入框内容
};

// 县change
const countryChange = () => {
  // console.log(addressData.value);
  Object.assign(userAddInfo.value.address, addressData.value);
  // console.log(userAddInfo.address);
};
// 添加收件人信息
const addAddress = async () => {
  const valid = await formRef.value.validate();
  // console.log(valid);
  // console.log(JSON.stringify(values, null, 2));
  const { provinceObj, cityObj, countryObj } = userAddInfo.value.address;
  if (provinceObj && cityObj && countryObj && valid) {
    userAddInfo.value.allAddress =
      provinceObj + cityObj + countryObj + userAddInfo.value.addressInfo;
    // console.log(userAddInfo);
    payStore.add(userAddInfo.value);
    isShow();
  } else {
    threeSelect.value = true;
  }
};
const orderComment = ref("");
const goodsListData = ref({});
// 去支付
const toPay = async () => {
  if (!payStore.userSelect?.allAddress) {
    alert("请添加收货人信息");
    return;
  }
  const { tradeNo, detailArrayList } = goodsListData.value;
  // 获取订单Id
  const orderId = await reqSubmitOrder({
    tradeNo,
    consignee: "坤坤",
    consigneeTel: "13888888888",
    deliveryAddress: "广东省深圳市宝安区草围村洗脚城",
    paymentWay: "ONLINE",
    orderComment: orderComment.value,
    orderDetailList: detailArrayList,
  });
  // console.log(orderId);
  // console.log(goodsListData.value.totalAmount);
  router.push({
    name: "Pay",
    query: {
      orderId,
      price: goodsListData.value.totalAmount,
    },
  });
};
const getGoodsListData = async () => {
  const res = await reqGetTradeInfo();
  // console.log(res);
  goodsListData.value = res;
  // console.log(goodsListData.value);
};
onMounted(() => {
  getGoodsListData();
});
</script>

<style lang="less" scoped>
.error-msg {
  margin-left: 5px;
  font-size: 12px;
  color: #f00;
}
.goodsPrice,
.goodsNum,
.isStock {
  line-height: 30px !important;
}
.tradeBox {
  width: 1200px;
  margin: 0 auto;

  .tradeTop {
    font-size: 14px;
    font-weight: bold;
  }

  .tradeBody {
    border: 1px solid #ccc;
    border-radius: 10px;
    margin: 10px 0;
    padding: 50px 20px;

    .userTitle,
    .payTitle,
    .userDestitle,
    .deliverGoods > span {
      font-size: 14px;
      font-weight: bold;
    }

    .userInfo {
      border-bottom: 1px solid #ccc;
      margin-bottom: 20px;
    }

    .header {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }

    .infoItem {
      display: flex;
      justify-content: space-around;
      align-items: center;
      padding-bottom: 20px;
      width: 50%;
      line-height: 30px;
      text-align: center;

      .addressee {
        border: 1px solid #333;
        width: 100px;
        height: 30px;
      }

      .defaultBtn {
        background-color: #878787;
        color: #fff;
      }
    }

    .payType {
      .payTypeList {
        display: flex;
        justify-content: flex-start;
        margin-top: 20px;

        .payItem {
          background-color: #fff;
          border: 1px solid #ccc;
          color: #666;
          width: 100px;
          height: 30px;
          text-align: center;
          line-height: 30px;
          margin: 0 15px;
        }
      }
    }

    .deliverGoods {
      .deliverGoodsInfo {
        padding: 20px;

        .deliveryType {
          padding: 20px 10px;
          border-bottom: 4px solid #fff;
          background-color: #efefef;

          .deliveryInfo {
            margin: 20px 0;
            display: flex;
            align-items: center;

            .deliveryTime {
              margin-left: 10px;
            }
          }
        }

        .goodsList {
          padding: 20px 10px;
          border-bottom: 4px solid #fff;
          background-color: #efefef;

          .goodsTitle {
            font-weight: bold;
          }

          .goodsItem {
            padding: 10px;
            display: flex;
            justify-content: space-between;

            .goodsImg {
              width: 150px;
              height: 150px;
            }

            .goodInfo {
              .goodsDes,
              .goodspRight {
                padding: 10px 20px;
              }
            }

            &::after {
              display: block;
              content: "";
            }
          }
        }
      }
    }

    .userDes {
      .userDestitle {
        display: block;
        line-height: 30px;
      }

      .userText {
        width: 96%;
        min-height: 100px;
        padding: 10px;
        border-radius: 10px;
        outline: 0px;
      }
    }
  }

  .tradeFooter {
    padding: 40px 0;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .goodsPriceInfo {
      width: 260px;

      .priceItem {
        display: flex;
        justify-content: space-between;
        height: 20px;
        line-height: 20px;
        font-size: 12px;
        font-weight: bold;

        .infoRight {
          color: #f00;
        }
      }
    }
    .goodsPrice {
      background-color: #eee;
      width: 100%;
      text-align: end;
      padding: 10px;

      .goodsPriceNum {
        font-size: 14px;
        font-weight: bold;
        padding: 10px 0;

        .goodsPeice {
          color: #f00;
        }
      }

      .goodsAddRess {
        color: #666;
        font-weight: bold;
      }
    }

    .toPayBtn {
      margin: 10px 0;
      width: 180px;
      height: 60px;
      line-height: 40px;
      font-size: 18px;
      font-weight: bold;
      color: white;
      background-color: #f00;
      border: none;
      border-radius: 0;
    }
  }
}

.active {
  position: relative;
  border: 1px solid #f00 !important;
  width: 100px;
  height: 30px;
  line-height: 30px;
  text-align: center;

  &::after {
    position: absolute;
    bottom: 0;
    right: 0;
    display: block;
    content: "√";
    color: #fff;
    background-image: linear-gradient(140deg, transparent 50%, green 50%);
    width: 20px;
    height: 20px;
    font-size: 13px;
    text-align: end;
  }
}

button {
  padding: 6px 20px;
  margin: 0 10px;
  min-width: 150px;
  height: 40px;
  border: none;
  background-color: #a092fa;
  color: #fff;
  font-size: 15px;
  font-weight: bold;
  border-radius: 5px;
}

.box {
  border-bottom: 1px solid #ccc;
  margin-bottom: 20px;
  padding-bottom: 20px;
}

.span {
  font-weight: bold;
}

.btn {
  width: 100px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border: 1px solid #ccc;
}

.defaultBtn {
  background-color: #fff;
  border: 1px solid #333;
  color: #333;
}

.inp {
  min-width: 180px;
  height: 30px;
  padding: 0 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
  outline: none;
}

.addressItem {
  min-width: 213px;
  height: 30px;
  text-align: center;
  border-radius: 5px;
  border: 1px solid #ccc;
  outline: none;
}
</style>
